/*
 * Created on 1 avr. 2007
 */
package fr.mywiki.view.web.servlet;

import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.mywiki.business.file.FileLite;
import fr.mywiki.business.file.FileManager;

/**
 * This servlet enables the display of a document whose identifier or name is
 * given as a request parameter.
 * 
 * @web.servlet name="DisplayDocument" display-name="DisplayDocument"
 * @web.servlet-mapping url-pattern="/DisplayDocument.do"
 */
public class DisplayDocumentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	/** Url Pattern of this servlet, can be used to build hyperlinks */
	public static final String URL_PATTERN = "DisplayDocument.do";
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		doPost(request, response);
	}

	/**
	 * Finds the <code>FileLite</code> object with the request-specified
	 * identifier or name.
	 * 
	 * TODO test it
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String fileName = request.getParameter(FileLite.FIELD_NAME);

		FileLite file = FileManager.findFileByName(fileName);
		if (file != null) {
			// File found
			byte[] fileContent = file.getContent();
			if (fileContent != null) {
				if (FileManager.isImageFile(file))
					response.setContentType("image/" + 
							FileManager.getFileExtension(file));
				else {
					response.setContentType("application/x-filler");
					response.setHeader("Content-Disposition", "attachment; filename="
							+ file.getName());
				}

				response.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
				response.setHeader("Cache-Control",
						"no-store, no-cache, must-revalidate");
				response.setHeader("Cache-Control", "post-check=0, pre-check=0");
				response.setHeader("Pragma", "no-cache");

				ServletOutputStream stream = response.getOutputStream();
				response.setContentLength(fileContent.length);
				stream.write(fileContent, 0, fileContent.length);
				stream.flush();
			}
		}
	}
}